"use strict";

import axios from "axios";
import router from "@/router";

// 创建 axios 实例
const axiosInstance = axios.create({
  baseURL: 'http://localhost:8081',
  timeout: 10000
});

// 请求拦截器 - 动态获取 token
axiosInstance.interceptors.request.use(
  config => {
    // 每次请求时都从 localStorage 读取最新的 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 定义插件
const AxiosPlugin = {
  install(app) {
    app.config.globalProperties.$axios = axiosInstance;
  }
};

// 响应拦截器
axiosInstance.interceptors.response.use(
  response => {
    // 正常响应处理
    return response
  },
  error => {
    // 错误处理
    if (error.response && error.response.status === 401) {
      // 清除可能的token存储
      localStorage.removeItem('token')
      // 跳转到登录页，并记录当前路径以便登录后返回
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.fullPath }
      })
      // 注意：消息提示应在组件中处理，拦截器中无法直接访问 Vue 实例
    }
    return Promise.reject(error)
  }
)

export default axiosInstance;
export { AxiosPlugin };
